<?php

namespace App\Remote;

use GuzzleHttp\MessageFormatterInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class RemoteMessageFormatter implements MessageFormatterInterface
{

    public string $executeClassName = "";

    public function __construct(string $executeClassName)
    {
        $this->executeClassName = $executeClassName;
    }

    /**
     * @inheritDoc
     */
    public function format(
        RequestInterface $request,
        ?ResponseInterface $response = null,
        ?\Throwable $error = null
    ): string {
        // TODO: Implement format() method.
        $request->getBody()->rewind();
        $requestOriginalContents = $request->getBody()->getContents();
        $responseHttpCode        = $responseOriginalContents = "";
        if (!is_null($response)) {
            $responseHttpCode         = $response->getStatusCode();
            $responseOriginalContents = $response->getBody()->getContents();
            $response->getBody()->rewind();
        }

        return "[ 远程调用 ] - [ " . $this->executeClassName . " ] " . json_encode([
                "request"  => [
                    "requestUrl"      => buildParsedUrl($request->getUri()),
                    "requestMethod"   => $request->getMethod(),
                    "requestHeaders"  => $request->getHeaders(),
                    "requestContents" => remoteContentsParser($requestOriginalContents, $requestOriginalContents)
                ],
                "response" => [
                    "responseHttpCode" => $responseHttpCode,
                    "responseContents" => remoteContentsParser($responseOriginalContents, $responseOriginalContents)
                ]
            ], JSON_UNESCAPED_UNICODE);

    }

}
